package com.hhd.cwqs.qs;

import com.hhd.cwqs.entity.CwqsUnit;
import com.hhd.cwqs.qs.sql.SingleConnJdbcTemplate;
import com.hhd.cwqs.service.ICwqsDataSourceService;
import com.hhd.cwqs.service.ICwqsUnitService;
import com.hhd.cwqs.utils.CommonUtils;
import org.jeecg.modules.quartz.entity.QuartzJob;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class ContextFactory {
    @Autowired
    ICwqsDataSourceService dataSourceService;

    @Autowired
    ICwqsUnitService unitService;

    private void resolveSqlTemplate(Context context) {
        context.setSourceSqlTemplate(new SingleConnJdbcTemplate(context.getSourceDataSource()));
        context.setTargetSqlTemplate(new SingleConnJdbcTemplate(context.getTargetDataSource()));
    }

    private void resolveUnits(String unitId, Context context) {
        if (CommonUtils.isEmpty(unitId)) {
            context.getUnits().addAll(unitService.list());
        } else {
            List<String> ids = Arrays.stream(unitId.split(",")).collect(Collectors.toList());
            context.setUnits(unitService.lambdaQuery().in(CwqsUnit::getId, ids).list());
        }
        CommonUtils.isEmptyThrow(context.getUnits(),
                new RuntimeException("没有找到需要同步数据的单位: " + unitId));
    }

    private void resolveBaseFields(String month, String year, String accountingSystem,Context context) {
        for (String s : month.split(",")) {
            context.getMonthes().add(s);
        }

        for (String s : year.split(",")) {
            context.getYears().add(s);
        }

        context.setAccountingSystem(accountingSystem);
    }

    private void resolveDataSource(String sourceDataSourceId, String targetDataSourceId, Context context) {
        context.setSourceDataSource(dataSourceService.getById(sourceDataSourceId));
        context.setTargetDataSource(dataSourceService.getById(targetDataSourceId));

        CommonUtils.isEmptyThrow(context.getSourceDataSource(), new RuntimeException("没有找到源数据源: " + sourceDataSourceId));
        CommonUtils.isEmptyThrow(context.getSourceDataSource(), new RuntimeException("没有找到目标数据源: " + targetDataSourceId));
    }

    public Context createContext(String sourceDataSourceId, String targetDataSourceId, String unitId, String month, String year, String accountingSystem) {
        Context context = new Context();

        resolveDataSource(sourceDataSourceId, targetDataSourceId,context);

        resolveBaseFields(month, year, accountingSystem, context);

        resolveUnits(unitId, context);

        resolveSqlTemplate(context);

        return context;
    }
}
